package com.zx.idc.backend.gui.sys;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zx.idc.backend.gui.common.BaseApi;
import com.zx.idc.backend.gui.common.Result;
import com.zx.idc.backend.gui.common.base.BaseUpdateApi;
import com.zx.idc.backend.gui.shiro.ShiroSessionManager;
import com.zx.idc.backend.gui.sys.login.MailClient;
import com.zx.idc.common.exception.NotSupportException;
import com.zx.idc.ds.sys.entity.SysConfiguration;
import com.zx.idc.ds.sys.service.ISysConfigurationService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统配置表 前端控制器
 * </p>
 *
 * @author rxliuli
 * @since 2019-04-09
 */
@RestController
@RequestMapping("/api/sysConfiguration")
public class SysConfigurationController extends BaseApi implements BaseUpdateApi<ISysConfigurationService, SysConfiguration> {
    @Autowired
    private ISysConfigurationService iSysConfigurationService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MailClient mailClient;

    @Override
    public Optional<ISysConfigurationService> getService() {
        return Optional.of(iSysConfigurationService);
    }

    @GetMapping("/list-for-all")
    @RequiresPermissions("system-configuration:sys-configuration")
    public Result<List<SysConfiguration>> listForAll() {
        return success(iSysConfigurationService.listForAll());
    }

    @GetMapping("/list/prefix/{prefix}")
    @RequiresPermissions("system-configuration:sys-configuration")
    public Result<List<SysConfiguration>> listPrefix(@PathVariable("prefix") String prefix) {
        return success(iSysConfigurationService.selectPrefix(prefix));
    }

    @GetMapping("/get-by-key/{key}")
    @RequiresPermissions(value = {"system-configuration:sys-configuration", "system-configuration:sys-user"}, logical = Logical.OR)
    public Result<SysConfiguration> getByKey(@PathVariable String key) {
        return success(iSysConfigurationService.selectOne(new SysConfiguration().setConfigKey(key)));
    }

    @PostMapping("/addOrUpdate/batch")
    @RequiresPermissions("system-configuration:sys-configuration:edit")
    public Result<Boolean> addOrUpdate(@RequestBody List<SysConfiguration> lists) {
        if (lists != null && !lists.isEmpty()) {
            List<String> keys = lists.stream()
                .filter(obj -> obj != null && !"".equals(obj.getConfigKey()))
                .map(SysConfiguration::getConfigKey).collect(Collectors.toList());
            //清理缓存
            redisTemplate.delete(keys);
            DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
            lists.forEach(obj -> {
                if (obj.getConfigKey().equals("sysSettings_loginsession_timeout")) {
                    ((ShiroSessionManager) securityManager.getSessionManager()).setGlobalSessionTimeout(Integer.parseInt(obj.getConfigValue()) * 60 * 60 * 1000);
                }
            });
        }
        return build(iSysConfigurationService.insertOrUpdateBatch(lists));
    }

    @PostMapping("/update-by-key")
    @RequiresPermissions("system-configuration:sys-configuration:edit")
    public Result<Boolean> updateByKey(@RequestBody SysConfiguration sysConfiguration) {
        if (sysConfiguration == null || StringUtils.isAnyEmpty(sysConfiguration.getConfigKey(), sysConfiguration.getConfigValue())) {
            return error("非法参数");
        }
        //清理缓存
        redisTemplate.delete(sysConfiguration.getConfigKey());
        return build(iSysConfigurationService.update(
            new SysConfiguration().setConfigValue(sysConfiguration.getConfigValue()),
            new EntityWrapper<>(new SysConfiguration().setConfigKey(sysConfiguration.getConfigKey()))
        ));
    }

    @PostMapping("/ntp-sync")
    @RequiresPermissions("system-configuration:sys-configuration:edit")
    public Result<Boolean> syncNTP(@RequestBody SysConfiguration sysConfiguration) {
        String msg;
        Exception ex;
        try {
            return success(iSysConfigurationService.syncNTP(sysConfiguration));
        } catch (NotSupportException e) {
            msg = e.getMessage();
            ex = e;
        } catch (Exception e) {
            msg = "Ntp服务器同步失败";
            ex = e;
        }
        log.error(msg, ex);
        return error(msg);

    }

    @GetMapping("/test-email/{email}")
    public Result<Boolean> sendTestEmail(@PathVariable("email") String email) {
        return success(mailClient.sendTestEmail(email));
    }
}

